package cn.school.publicPhone.service.impl;

import cn.school.classManage.service.SchoolClassService;
import cn.school.classManage.vo.SchoolClassVO;
import cn.school.common.api.CommonPage;
import cn.school.common.api.CommonResult;
import cn.school.common.utils.SysUserUtils;
import cn.school.publicPhone.dao.StudentContactsDao;
import cn.school.student.dao.StudentInfoDao;
import cn.school.student.entity.StudentContacts;
import cn.school.student.entity.vo.StudentInfoVo;
import cn.school.publicPhone.service.StudentContactsService;
import cn.school.student.vo.StudentContactsImportVO;
import cn.school.student.vo.StudentContactsVO;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.SyncReadListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class StudentContactsServiceImpl extends ServiceImpl<StudentContactsDao, StudentContacts> implements StudentContactsService {

    @Resource
    StudentInfoDao studentInfoDao;
    public StudentContactsServiceImpl() {
        super();
    }

    @Override
    public CommonPage<StudentContacts> getStudentContactsPage(StudentContactsVO studentContacts) {
        LambdaQueryWrapper<StudentContacts> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(studentContacts.getClassId())){
            wrapper.eq(StudentContacts::getClassId, studentContacts.getClassId());
        }
        if(!StringUtils.isEmpty(studentContacts.getStudentName())){
            wrapper.like(StudentContacts::getStudentName, studentContacts.getStudentName());
        }

        wrapper.orderByDesc(StudentContacts::getCreateTime);
        IPage<StudentContacts> page =  page(new Page<>(studentContacts.getPageNum(), studentContacts.getPageSize()), wrapper);
        return CommonPage.restPage(page);
    }

    @Override
    public int addOrUpdateStudentContacts(StudentContacts studentContacts) {
        String username = SysUserUtils.getSysUser().getUsername();
        int num = 0 ;
        if(StringUtils.isEmpty(studentContacts.getId())){
            studentContacts.setCreateBy(username);
            studentContacts.setCreateTime(new Date());
            num = this.baseMapper.insert(studentContacts);
        }else{
            studentContacts.setModifyBy(username);
            studentContacts.setModifyTime(new Date());
            num = this.baseMapper.updateById(studentContacts);
        }
        return num;
    }

    @Override
    public int deleteContactsById(Long id) {
        if(id!=null){
            int num = this.baseMapper.deleteById(id);
            return num;
        }
        return 0;
    }

    @Override
    public List<StudentContacts> findContactsList(StudentContactsVO studentContacts) {
        LambdaQueryWrapper<StudentContacts> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(studentContacts.getClassId())){
            wrapper.eq(StudentContacts::getClassId, studentContacts.getClassId());
        }
        if(!StringUtils.isEmpty(studentContacts.getStudentName())){
            wrapper.like(StudentContacts::getStudentName, studentContacts.getStudentName());
        }
        if(!StringUtils.isEmpty(studentContacts.getContactsPhone())){
            wrapper.like(StudentContacts::getContactsPhone, studentContacts.getContactsPhone());
        }
        if(!StringUtils.isEmpty(studentContacts.getClassName())){
            wrapper.like(StudentContacts::getClassName, studentContacts.getClassName());
        }
        return this.baseMapper.selectList(wrapper);
    }

    @Override
    public CommonResult importContactsList(InputStream inputStream) {
        //获取班级信息
        List<StudentContactsImportVO> readList=new ArrayList<>();
        readList = EasyExcel.read(inputStream)
                .registerReadListener(new SyncReadListener())
                .head(StudentContactsImportVO.class)
                .sheet(0)
                .headRowNumber(1)
                .doReadSync();
//        EasyExcel.read(inputStream, StudentContactsImportVO.class, new SyncReadListener() {
//
//            @Override
//            public void invoke(Object object, AnalysisContext context) {
//                //读取到的数据被存入bean
//                StudentContactsImportVO studentInfo=(StudentContactsImportVO)object;
//
//                for (SchoolClassVO vo : classList) {
//                    if(vo.getClassName().equals(studentInfo.getClassName())){
//                        studentInfo.setClassName(vo.getClassName());
//                        studentInfo.setClassId(String.valueOf(vo.getId()));
//                    }
//                }
//                readList.add(studentInfo);
//            }
//        }).doReadAll();
        //查询指定的班级中是否有这些学生
        List<StudentInfoVo> studentList = studentInfoDao.getClassInStudent(readList);
        if(studentList.size()!=readList.size()){
            return CommonResult.failed("班级与学生信息不匹配，请检查修改后再导入");
        }
        for (StudentContactsImportVO studentContactsImportVO : readList) {
            for (StudentInfoVo studentInfoVo : studentList) {
                if(studentInfoVo.getClassId().equals(studentContactsImportVO.getClassId())){
                    studentContactsImportVO.setStudentId(studentInfoVo.getStudentId());
                }
                if(studentInfoVo.getStudentId().equals(studentContactsImportVO.getStudentId())&& studentContactsImportVO.getClassId()==null){
                    studentContactsImportVO.setClassId(studentInfoVo.getClassId());
                }
            }
            Pattern PATTERN = Pattern.compile("^1[3-9]\\d{9}$");
            Matcher matcher = PATTERN.matcher(studentContactsImportVO.getContactsPhone());
            boolean result = matcher.matches();
            if(!result){
                return CommonResult.failed("学生【"+studentContactsImportVO.getStudentName()+"】联系人手机号码格式错误");
            }
        }

        StudentContacts sc = null;
        for (StudentContactsImportVO studentContactsImportVO : readList) {
            sc = new StudentContacts();
            BeanUtils.copyProperties(studentContactsImportVO, sc);
            this.baseMapper.insert(sc);
        }

        return CommonResult.success("导入成功，请刷新列表查看");


    }

    @Resource
    SchoolClassService schoolClassService;
    private List<SchoolClassVO> getClassList(){
        return schoolClassService.findAllSchoolClass();
    }
}
